package soft.quicknote.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import org.joda.time.DateTime;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import jp.wasabeef.richeditor.RichEditor;
import soft.quicknote.DBHelper;
import soft.quicknote.Operation;
import soft.quicknote.R;
import soft.quicknote.beans.Category;
import soft.quicknote.beans.Note;

public class NoteEditor extends AppCompatActivity {

    private final static String TAG = NoteEditor.class.getSimpleName();
    private final static Map<String, Integer> FONT_SIZE = new HashMap<>();

    static {
        FONT_SIZE.put("small", 14);
        FONT_SIZE.put("normal", 16);
        FONT_SIZE.put("large", 18);
    }

    private RichEditor mEditor;
    DBHelper helper = new DBHelper(this);
    Note note;
    boolean editFlag = false;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.note_editor);
        Intent intent = getIntent();
        String op = intent.getStringExtra("op");
        int noteId = -1;
        if (Operation.CREATE.equals(op)) {
            noteId = -1;
        } else if (Operation.EDIT.equals(op)) {
            noteId = intent.getIntExtra("id", -1);
        }


        if (noteId != -1) {
            note = helper.getNoteById(noteId);
            if (note == null) {
                note = new Note();
            }
        } else {
            note = new Note();
        }


        mEditor = (RichEditor) findViewById(R.id.richeditor);
        mEditor.setHtml(note.getContent());

        mEditor.setOnTextChangeListener(new RichEditor.OnTextChangeListener() {
            @Override
            public void onTextChange(String text) {
                editFlag = true;
                int i = text.indexOf("<br>");
                if (i == -1) return;
                String title = text.substring(0, i);
                setTitle(getString(R.string.editor_title_formatter, title));
                note.setTitle(title);
            }
        });
        mEditor.setPadding(5, 5, 5, 5);

        String fontSizeMode = getSharedPreferences("quicknote", MODE_PRIVATE).getString("fontSize", "normal");
        mEditor.setEditorFontSize(FONT_SIZE.get(fontSizeMode));

        setTitle(R.string.editor_title);
    }

    /**
     * 打开菜单栏
     *
     * @param menu
     * @return 打开成功
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_editor, menu);
        return true;
    }

    /**
     * 选择菜单栏中的选项
     *
     * @param item
     * @return 点击成功
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_item_save:
                saveNote();
                return true;
            case R.id.menu_item_change_category:
                showChangeCategoryDialog();
                return super.onOptionsItemSelected(item);
            case android.R.id.home:
                confirmQuit();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void showChangeCategoryDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("修改分类");
        final Category[] items = helper.queryAllCategory().toArray(new Category[0]);
        final String[] names = new String[items.length];
        for (int i = 0; i < items.length; i++) names[i] = items[i].getName();
        builder.setSingleChoiceItems(names, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                note.setCategory(items[which].getId());
                if (helper.saveNote(note)) {
                    Toast.makeText(NoteEditor.this, "设置分类为：" + names[which], Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(NoteEditor.this, "保存失败", Toast.LENGTH_LONG).show();
                }
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (editFlag) {
                confirmQuit();
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    void confirmQuit() {
        if(!editFlag || mEditor.getHtml().equals("")){
            finish();
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确定不保存退出？");
        builder.setPositiveButton("保存并退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                saveNote();
                finish();
            }
        }).setNegativeButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                finish();
            }
        }).create().show();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Log.d(TAG, "BACK返回");
    }

    /**
     * 保存便签
     *
     * @return 保存成功
     */
    void saveNote() {
        String content = mEditor.getHtml();
        if (content.length() == 0) {
            return;
        }

        note.setContent(content);
        Timestamp ts = new Timestamp(new DateTime().getMillis());
        Log.d(TAG, "timestamp:" + ts.getTime());
        note.setUpdateTime(ts.getTime());

        if (note.getId() == -1) {
            int id = helper.insertNote(note);
            note.setId(id);
        } else {
            helper.saveNote(note);
        }
        Log.i(TAG, "保存成功");
    }

}
